/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.passwords;

import org.json.JSONObject;
import org.webos.java.base.Dialog;
import org.webos.java.base.DialogType;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.RemoteMessage;
import org.webos.java.root.Log;

/**
 *
 * @author kostya
 */
@DialogType(jsClass="passwords.MasterPassword")
public class MasterPassword extends Dialog<PasswordManager>{

    boolean newPassword = false;
    String originalPassword = null;
    String enteredPassword = null;

    public MasterPassword(PasswordManager aManager) {
        super(aManager);
    }

    public synchronized String getPassword(String aPassword){
        originalPassword = aPassword;
        if(aPassword==null){
            newPassword = true;
        }
        getData().putOpt("new_pass", newPassword);
        show();
        try {
            wait();
            return enteredPassword;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @RemoteMessage
    public JSONObject okClick(JSONObject aData){
        try {
            String password = aData.optString("pass1", "");
            if("".equals(password)){
                return NetworkManager.getErrorObject(1008, "Password can't be empty");
            }
            if(newPassword){
                if(!password.equals(aData.optString("pass2", ""))){
                    return NetworkManager.getErrorObject(1007, "Passwords doesn't match");
                }
            }else{
                if(!password.equals(originalPassword)){
                    return NetworkManager.getErrorObject(1009, "You entered invalid password");
                }
            }
            enteredPassword = password;
            closeDialog(aData);
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @Override
    @RemoteMessage
    public synchronized void closeDialog(JSONObject data) {
        super.closeDialog(data);
        notify();
    }


}
